package rpc

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"google.golang.org/grpc"
	"log"
	"net"
	"saleforce/sf-backend-user/config"
	"saleforce/sf-backend-user/service"
	lg "saleforce/sf-common/protoc/backend-user"
)

func RpcStart(config *config.NacosConfig, server *config.ServerConfig) {
	clientConfig := *constant.NewClientConfig(
		constant.WithNamespaceId(config.Namespace),
		constant.WithTimeoutMs(config.TimeoutMs),
		constant.WithNotLoadCacheAtStart(true),
	)
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: config.IP,
			Port:   config.Port,
		},
	}
	namingClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		log.Fatalf("❌ 创建 Nacos 客户端失败: %v", err)
	}
	_, err = namingClient.RegisterInstance(vo.RegisterInstanceParam{
		Ip:          config.LocalIp,
		Port:        server.Port,
		ServiceName: config.ServiceName,
		Weight:      config.Weight,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true, // 临时节点：服务挂掉会自动删除
		ClusterName: "DEFAULT",
		GroupName:   "DEFAULT_GROUP",
		Metadata:    map[string]string{"version": "1.0.0"},
	})
	if err != nil {
		log.Fatalf("❌ 注册服务到 Nacos 失败: %v", err)
	}
	log.Printf("✅ 成功注册服务到 Nacos，运行端口：%d\n", server.Port)
	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", config.GrpcPort))
	if err != nil {
		log.Fatalf("❌ 启动监听失败: %v", err)
	}
	grpcServer := grpc.NewServer()
	//protocol载入
	lg.RegisterLoginServiceServer(grpcServer, &service.LoginService{})
	lg.RegisterMenuServiceServer(grpcServer, &service.MenuService{})

	log.Printf("🚀 gRPC 服务已启动，监听端口：%d", config.GrpcPort)
	if err := grpcServer.Serve(lis); err != nil {
		log.Fatalf("❌ gRPC 服务启动失败: %v", err)
	}
}
